//
//  String+Extentions.swift
//  TeaShop
//
//  Created by 刘泽 on 2018/1/24.
//  Copyright © 2018年 刘泽. All rights reserved.
//

import Foundation
import UIKit
import CommonCrypto

extension String {

    public var attr : NSMutableAttributedString! {
        get{
            let attrss = NSMutableAttributedString(string: self)
            return attrss
        }
    }

    //MARK:String转Int 转不成功的话返回0
    public func toInt() -> Int{
        if Int(self) != nil {
            return Int(self)!
        }else{
            return 0
        }
    }
    //MARK:String转Double 转不成功的话返回0
    public func toDouble() -> Double {
        if Double(self) != nil {
            return Double(self)!
        }else{
            return 0
        }
    }
    
    //MARK:String格式化保留两位小数 转不成功的话返回0.00
    public func formatMoney() -> String {
        let temp = Double(self)
        if  temp != nil {
            return String(format:"%.2f",temp!)
        }else{
            return "0.00"
        }
    }

    //MARK:转换为分
    public func toPoint() -> Int{
        let temp = Double(self)
        if temp != nil{
            return lrint(temp! * 100)
        }else{
            return 0
        }
    }
    
    //MARK:字符串 MD5 加密
    public func md5() ->String!{
        let str = self.cString(using: .utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: .utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize(count: digestLen)
        return String(format: hash as String)
    }
    
    //MARK:字符串转Base64
    public func base64() -> String{
        let data = self.data(using: String.Encoding.utf8)
        let base64String = data?.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
        return base64String!
    }
    
    /**
     限制宽度 计算 String 的 Size
     - parameter width: width
     - parameter font:     font
     
     - returns: size value
     */
    public func sizeWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGSize {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let size: CGSize = self.boundingRect(
            with: constraintRect,
            options: NSStringDrawingOptions.usesLineFragmentOrigin,
            attributes: [NSAttributedStringKey.font: font],
            context: nil
            ).size
        return size
    }
    
    /**
     限制宽度 计算 String 的 Height
     
     - parameter width: width
     - parameter font:  font
     
     - returns: height value
     */
    public func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: .usesLineFragmentOrigin,
            attributes: [NSAttributedStringKey.font: font],
            context: nil)
        return boundingBox.height
    }
    
    /**
     计算当前Font下 String 的宽度
     - parameter font:  font
     
     - returns: height value
     */
    public func widthWithCurrentFont(_ font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: font.pointSize)
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: .usesLineFragmentOrigin,
            attributes: [NSAttributedStringKey.font: font],
            context: nil)
        return boundingBox.width
    }
    
    //MARK:添加删除线
    public func addDelLine() -> NSMutableAttributedString{
        let attrString = NSMutableAttributedString.init(string: self)
        attrString.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.lightGray], range: NSMakeRange(0, count))
        attrString.addAttributes([NSAttributedStringKey.strikethroughStyle: 1], range: NSMakeRange(0, count))
        return attrString
    }
    
    //MARK:添加加粗
    public func addBold(fontSize:CGFloat) -> NSMutableAttributedString{
        let attrString = NSMutableAttributedString.init(string: self)
        attrString.addAttributes([NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: fontSize)], range: NSMakeRange(0, count))
        return attrString
    }

    //MARK:添加下划线
    public func addUnderLine() -> NSMutableAttributedString{
        let attrStr = NSMutableAttributedString.init(string: self)
        attrStr.addAttributes([NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle], range: NSMakeRange(0, count))
        return attrStr
    }

    //MARK:与某几个字一致的显示亮色
    public func heightLight(changeColor:UIColor,if sameWith:String) -> NSMutableAttributedString{
        let attrString = NSMutableAttributedString.init(string: self)
        let nsstr = NSString.init(string: self)
        let range : NSRange = nsstr.range(of: sameWith)
        attrString.addAttributes([NSAttributedStringKey.foregroundColor:changeColor], range: range)
        return attrString
    }

    //MARK:手机号中间四位换成****
    public func replaceStar() -> String{
        if self.count == 11{
            let before = self.prefix(3)
            let end = self.suffix(4)
            return before + "****" + end
        }else{
            return self
        }
    }

    //MARK:html转富文本
    public func htmlToAttrStr(_ fontSize:CGFloat = 14) -> NSAttributedString{
        let data = self.data(using: .unicode)
        do{

            let attr = try NSMutableAttributedString(data: data!, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
            attr.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: fontSize)], range: NSRange.init(location: 0, length: attr.length))
            return attr
        }catch{

        }
        return NSAttributedString(string: "")
    }

    //MARK:字符串转时间
    public func toDate(dateFormat:String = "yyyy-MM-dd HH:mm:ss") -> Date{
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: self)
        return date!
    }

    //MARK:字符串转多久之前
    public func toTimeAgo() -> String{
        return Date.timeAgoSinceDate(self.toDate())
    }


    public func getFirstLetterFromString() -> (String) {
        // 注意,这里一定要转换成可变字符串
        let mutableString = NSMutableString.init(string: self)
        // 将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
        // 去掉声调(用此方法大大提高遍历的速度)
        // 并将拼音首字母装换成大写
        let pinyinString = mutableString.folding(options: String.CompareOptions.diacriticInsensitive, locale: NSLocale.current).uppercased()
        // 截取大写首字母
        let firstString = String(pinyinString.first!)
        // 判断姓名首位是否为大写字母
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        return predA.evaluate(with: firstString) ? firstString : "#"

    }

    //MARK:包裹html
    func htmlFormatting() -> String{
        let html1  = """
        <!DOCTYPE html>
        <html>
        <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
        <style>

        img{
        max-width:100%;
        height:auto;
        }

        </style>

        <style>

        p{
        text-align: justify;
        text-align-last: justify;
        }

        </style>
        </head>

        <body>

        \(self)

        </body>
        </html>
        """
        return html1
    }

}




